import { Login, Logout } from "@/Api/login.js";
import {
  getToken,
  setToken,
  removeToken,
  getUserid,
  setUserid,
  removeUserid,
} from "@/utils/auth";
import { Message } from "element-ui";
// import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  userid: getUserid(),
  username: "",
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
    setToken(token)
  },
  SET_USERID: (state, userid) => {
    state.userid = userid;
    setUserid(userid);
  },
  SET_USERNAME: (state, username) => {
    state.username = username;
  },
};

const actions = {
  // 登錄
  login({ commit }, userInfo) {
    const { phone, password } = userInfo;
    return new Promise((resolve, reject) => {
      Login({ phone: phone.trim(), password: password })
        .then((response) => {
          //  console.log('response==>',response)
          if (response.code == "200") {
            // const { result} = { result: { token: response.token,userid:response.profile.userId}};
            commit("SET_TOKEN", response.token);
            commit("SET_USERID", response.profile.userId);
            resolve();
            // resolve({ });
          } else {
            Message({
              message: "登录失败！",
              type: "error",
              duration: 1500,
            });
            reject(response);
          }
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      Logout()
        .then((response) => {
          if (response.code == "200") {
            // console.log("response==>", response);
            // logout(state.token).then(() => {
            commit("SET_TOKEN", "");
            commit("SET_USERID", "");
            commit("SET_USERNAME", "");
            removeToken();
            removeUserid();
            // resetRouter()
            resolve();
          }
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "");
      commit("SET_USERID", "");
      commit("SET_USERNAME", "");
      removeToken();
      removeUserid();
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
